# -*- coding: utf-8 -*-
"""
单个文本向量化示例
"""

import asyncio
import sys
import os

# 添加项目根目录到系统路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

from embedding import EmbeddingClient, VectorStore


async def single_text_example():
    """单个文本向量化示例"""
    print("=== 单个文本向量化示例 ===")
    
    # 初始化客户端
    client = EmbeddingClient()
    store = VectorStore()
    
    # 示例文本
    text = "这是一个关于信访举报的示例文本，包含了一些重要的信息。"
    
    try:
        # 同步向量化
        print("\n1. 同步向量化:")
        result = client.embed_text(text)
        print(f"文本: {result.text}")
        print(f"向量维度: {len(result.vector)}")
        print(f"模型: {result.model}")
        print(f"向量前5个值: {result.vector[:5]}")
        
        # 异步向量化
        print("\n2. 异步向量化:")
        result_async = await client.embed_text_async(text)
        print(f"文本: {result_async.text}")
        print(f"向量维度: {len(result_async.vector)}")
        print(f"模型: {result_async.model}")
        print(f"向量前5个值: {result_async.vector[:5]}")
        
        # 存储向量
        print("\n3. 存储向量:")
        vector_ids = store.add_vectors([result], tags=["示例"], extra_info={"source": "single_text_example"})
        print(f"存储的向量ID: {vector_ids}")
        
        # 搜索相似向量
        print("\n4. 搜索相似向量:")
        similar_results = store.search_similar(result.vector, top_k=3)
        for vector_id, similarity, metadata in similar_results:
            print(f"向量ID: {vector_id}, 相似度: {similarity:.4f}, 文本: {metadata.text[:50]}...")
        
        # 获取存储统计
        print("\n5. 存储统计:")
        stats = store.get_stats()
        for key, value in stats.items():
            print(f"{key}: {value}")
            
    except Exception as e:
        print(f"示例执行失败: {e}")


def sync_single_text_example():
    """同步单个文本向量化示例"""
    print("=== 同步单个文本向量化示例 ===")
    
    # 初始化客户端
    client = EmbeddingClient()
    store = VectorStore()
    
    # 示例文本
    text = "这是另一个示例文本，用于测试同步向量化功能。"
    
    try:
        # 向量化
        result = client.embed_text(text)
        print(f"文本: {result.text}")
        print(f"向量维度: {len(result.vector)}")
        print(f"模型: {result.model}")
        
        # 存储向量
        vector_ids = store.add_vectors([result], tags=["同步示例"])
        print(f"存储的向量ID: {vector_ids}")
        
        # 验证存储
        stored_vector, metadata = store.get_vector(vector_ids[0])
        if stored_vector is not None:
            print(f"成功检索到存储的向量，维度: {len(stored_vector)}")
        
    except Exception as e:
        print(f"同步示例执行失败: {e}")


if __name__ == "__main__":
    # 运行同步示例
    sync_single_text_example()
    
    # 运行异步示例
    asyncio.run(single_text_example())
